<script setup lang="tsx">
import { ContentWrap } from '@/components/ContentWrap'
import { useI18n } from '@/hooks/web/useI18n'
import { ref, reactive, unref, nextTick, watch } from 'vue'
import {
  ElTree,
  ElInput,
  ElDivider,
  ElTag,
  ElForm,
  ElFormItem,
  ElRow,
  ElCol,
  ElRadioGroup,
  ElRadio,
  ElButton,
  ElTreeSelect,
  ElMessageBox,
  ElMessage
} from 'element-plus'
import { getDepartmentApi, saveDeptApi, updateDeptApi, deleteDeptApi } from '@/api/department'
import type { DepartmentItem } from '@/api/department/types'
import { Refresh, Search } from '@element-plus/icons-vue'

const { t } = useI18n()

const treeEl = ref<typeof ElTree>()

const currentNodeKey = ref('')
const departmentList = ref<DepartmentItem[]>([])
const treeLoading = ref(false)
const loadDeptList = async () => {
  treeLoading.value = true
  const res = await getDepartmentApi()
  departmentList.value = res.data
  currentNodeKey.value = (res.data[0] && res.data[0]?.child && res.data[0].child[0].id) || ''
  await nextTick()
  unref(treeEl)?.setCurrentKey(currentNodeKey.value)
  treeLoading.value = false
}
loadDeptList()

const currentDepartment = ref('')

const form = reactive({
  id: '',
  pid: '',
  name: '',
  status: 1,
  sort: '',
  remark: ''
})

watch(
  () => currentDepartment.value,
  (val) => {
    unref(treeEl)!.filter(val)
  }
)

const pidDisabled = ref(false)

watch(
  () => form.pid,
  (val) => {
    // 如果父级是0，就禁用父级选项
    if (val === '0') {
      pidDisabled.value = true
    } else {
      pidDisabled.value = false
    }
  }
)

const add = () => {
  form.id = ''
  form.pid = ''
  form.name = ''
  form.status = 1
  form.sort = ''
  form.remark = ''
}

const delLoading = ref(false)

const delData = async () => {
  delLoading.value = true

  if (form.id) {
    await ElMessageBox.confirm(`删除部门 [${form.name}] <br>是否继续?`, '提示', {
      dangerouslyUseHTMLString: true,
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
      center: true
    }).then(async () => {
      await deleteDeptApi({ id: form.id })
      ElMessage.success('删除成功')
      refresh()
      add()
    })
  }

  delLoading.value = false
}

const saveLoading = ref(false)

const save = async () => {
  saveLoading.value = true
  try {
    if (form.id) {
      await updateDeptApi(form)
    } else {
      await saveDeptApi(form)
    }
  } finally {
    saveLoading.value = false
    refresh()
  }
}

const refresh = () => {
  loadDeptList()
}

const deleteDisabled = ref(false)

const filterNode = (value: string, data: DepartmentItem) => {
  if (!value) return true
  return data.name.includes(value)
}

const nodeClick = (data, node) => {
  // isLeaf 有叶子节点false，没有叶子节点true
  deleteDisabled.value = !node.isLeaf
  form.id = data.id
  form.pid = data.pid
  form.name = data.name
  form.status = data.status
  form.sort = data.sort
  form.remark = data.remark
}

const rules = {
  code: {
    required: true,
    message: '不能为空',
    trigger: 'blur'
  },
  name: {
    required: true,
    message: '不能为空',
    trigger: 'blur'
  }
}
</script>

<template>
  <div class="flex w-100% h-100%">
    <ContentWrap class="w-30%">
      <div class="flex justify-center items-center">
        <div class="flex-1">{{ t('userDemo.departmentList') }}</div>
        <ElInput
          v-model="currentDepartment"
          class="flex-[2]"
          :placeholder="t('userDemo.searchDepartment')"
          :prefix-icon="Search"
          clearable
        />
      </div>
      <ElDivider />
      <ElTree
        v-loading="treeLoading"
        ref="treeEl"
        :data="departmentList"
        default-expand-all
        :expand-on-click-node="false"
        node-key="id"
        :current-node-key="currentNodeKey"
        :props="{
          label: 'name',
          children: 'child'
        }"
        :filter-node-method="filterNode"
        @node-click="nodeClick"
      >
        <template #default="{ data }">
          <div :title="data.name" class="whitespace-nowrap overflow-ellipsis overflow-hidden">
            {{ data.name }}
            <ElTag v-if="data.status != 1" type="info">禁用</ElTag>
          </div>
        </template>
      </ElTree>
    </ContentWrap>
    <ContentWrap class="flex-[3] ml-10px">
      <div class="mb-10px">
        <el-button size="small" :icon="Refresh" @click="refresh">刷新</el-button>
        <el-button type="primary" size="small" @click="add">{{ t('exampleDemo.add') }}</el-button>
        <el-button type="primary" size="small" :loading="saveLoading" @click="save">{{
          t('保存')
        }}</el-button>
        <el-button
          :loading="delLoading"
          :disabled="deleteDisabled"
          size="small"
          type="danger"
          @click="delData()"
        >
          {{ t('exampleDemo.del') }}
        </el-button>
      </div>
      <ElForm :model="form" :rules="rules" v-loading="treeLoading" label-position="top">
        <el-row :gutter="20" style="margin-top: 10px">
          <el-col :span="12">
            <el-form-item label="父级" prop="pid">
              <!--
              clearable 有清除选项
              check-strictly 可以选择任意节点，否则只能选叶子节点
              default-expand-all 展开所有节点
                -->
              <el-tree-select
                v-model="form.pid"
                size="small"
                node-key="id"
                clearable
                check-strictly
                default-expand-all
                :no-match-text="'aaaa'"
                :no-data-text="'xxxxx'"
                :disabled="pidDisabled"
                :data="departmentList"
                :render-after-expand="false"
                :props="{
                  label: 'name',
                  children: 'child'
                }"
              />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20" style="margin-top: 10px">
          <el-col :span="12">
            <el-form-item label="名称" prop="name">
              <el-input v-model="form.name" size="small" autocomplete="off" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="状态" prop="status">
              <el-radio-group v-model="form.status">
                <el-radio :value="0">禁用</el-radio>
                <el-radio :value="1">启用</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20" style="margin-top: 10px">
          <el-col :span="12">
            <el-form-item label="顺序" prop="sort">
              <el-input v-model="form.sort" size="small" autocomplete="off" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20" style="margin-top: 10px">
          <el-col :span="24">
            <el-form-item label="备注" prop="remark">
              <el-input
                v-model="form.remark"
                type="textarea"
                :rows="2"
                size="small"
                autocomplete="off"
              />
            </el-form-item>
          </el-col>
        </el-row>
      </ElForm>
    </ContentWrap>
  </div>
</template>
